package com.gzy.studentsociety.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*", initParams = {@WebInitParam(name = "encoding", value = "UTF-8")})
public class EncodingFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.encoding = config.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 设置请求和响应的字符集编码
        req.setCharacterEncoding(encoding);
        res.setCharacterEncoding(encoding);

        // 对GET请求进行特殊处理
        if ("get".equalsIgnoreCase(req.getMethod())) {
            request = new HttpServletRequestWrapper(req) {
                @Override
                public Map<String, String[]> getParameterMap() {
                    Map<String, String[]> map = super.getParameterMap();
                    for (String key : map.keySet()) {
                        String[] arr = map.get(key);
                        for (int i = 0; i < arr.length; i++) {
                            try {
                                arr[i] = new String(arr[i].getBytes("ISO8859-1"), encoding);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    return map;
                }
            };
        }

        // 继续过滤器链
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 当过滤器被移除时，可以做一些清理工作
    }
}